package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //组装树形菜单
        /**
         * filter 找到所有最外层节点，也就是一级分类
         * map 调用递归方法给当前菜单设置子菜单
         * sorted 根据sort字段进行拍讯
         */
        List<CategoryEntity> categoryTree = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0).map(menu -> {
            //从所有菜单中，找到当前菜单的子菜单
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return categoryTree;
    }

    @Override
    public void removeMenusByIds(Long[] catIds) {
         //TODO 删除的时候要判断一下当前菜单是否有被引用，如果有被引用还不能删除
         baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    /**
     * 递归查找当前菜单的子菜单
     * @param currentMenu
     * @param all
     * @return
     */
    public List<CategoryEntity> getChildrens(CategoryEntity currentMenu, List<CategoryEntity> all){
        //从所有菜单中找到父ID和当前菜单的id说明就是当前菜单的子菜单，然后进行map递归查找
        List<CategoryEntity> collect = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == currentMenu.getCatId()).map(menu -> {
            menu.setChildren(getChildrens(menu, all));
            return menu;
        }).sorted((menu1, menu2) -> {
            //注意sort字段有可能是空的，所以做个非空判断
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}